package com.horoscope.astrology.zodiac.signs.free.activity

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.work.WorkManager
import com.horoscope.astrology.zodiac.signs.free.AppSettingManager
import com.horoscope.astrology.zodiac.signs.free.R
import com.horoscope.astrology.zodiac.signs.free.adapter.AspectAdapter
import com.horoscope.astrology.zodiac.signs.free.adapter.ContentAdapter
import com.horoscope.astrology.zodiac.signs.free.bean.BirthChartResultBean
import com.horoscope.astrology.zodiac.signs.free.bean.UserBean
import com.horoscope.astrology.zodiac.signs.free.infc.OnItemClickedListener
import com.horoscope.astrology.zodiac.signs.free.network.NetworkEngine
import com.horoscope.astrology.zodiac.signs.free.network.NetworkListener
import com.horoscope.astrology.zodiac.signs.free.utils.*
import com.horoscope.astrology.zodiac.signs.free.utils.ad.ad_business.ADRewardManager
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.activity_bitth_chat.*
import kotlinx.android.synthetic.main.back_title.*
import kotlinx.android.synthetic.main.item_loading.*
import kotlinx.android.synthetic.main.item_share.*
import kotlinx.android.synthetic.main.view_network_error.*
import kotlinx.coroutines.*

class BirthChatActivity : Base2Activity() {

    private var mUserBean: UserBean = UserBean()
    private var contentAdapter: ContentAdapter? = null
    private var aspectAdapter: AspectAdapter? = null
    private var num = 0
    private var job: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        immersionWhite()
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bitth_chat)
        initTitleBar(
            this@BirthChatActivity,
            R.id.btn_back_edit_name,
            R.id.text_view_back_title,
            getString(R.string.astrology_person_birth_chart)
        )
        text_view_back_title.setTextColor(Color.BLACK)
        btn_back_edit_name.setImageResource(R.drawable.icon_back_black)

        initViewAndData()

        // Interstitial1(SplashActivity就去加载了广告数据)
        activityShowAd("Interstitial_BirthChart")

        AppSettingManager.saveInt(1, "birth_chat") // 成功使用了个人名命盘
    }

    override fun onResume() {
        super.onResume()
        // 观看视频后刷新指定位置数据
        LiveEventBus.get(TYPE, Int::class.java)
            .observeSticky(
                this@BirthChatActivity,
                Observer<Int?> { t ->
                    t?.let {
                        showLoaded()
                        contentAdapter!!.notifyPositionData(t)
                    }
                })
    }

    private fun initViewAndData() {
        getParameter()
        // 顶部连接用户名
        tv_chart_name?.text = StringBuilder("Chart Data For ${mUserBean.name}")

        contentAdapter = ContentAdapter(this)
        initRecycler(recycler_content)
        initRecycler2(recycler_aspect)

        request(mUserBean)

        // 计算其它人
        text_view_calculate?.setOnClickListener {
            val birthChatToProfile = Intent(this, InputProfileActivity::class.java)
            birthChatToProfile.putExtra("fromContext", "BirthChatActivity")
            startActivity(birthChatToProfile)
            // 在命盘结果页点击计算其他人进入的 profile 页
//            FlurryEventUtil.putDataToEvent(EventType.TYPE_ASTROLOGY_PROFILE_SHOW, null, null)
        }

        tv_network_ok.setOnClickListener {
            include_error.visibility = View.GONE
            request(mUserBean)
        }

        ShareManager.initShare(
            this@BirthChatActivity,
            line_left,
            line_right,
            text_view_share,
            image_view_more_share,
            tv_facebook
        )
    }

    private fun getParameter() {
        val mName: String = intent.getStringExtra("name") ?: ""
        val mGender: String = intent.getStringExtra("gender") ?: ""
        val mBirth: String = intent.getStringExtra("birth") ?: ""
        val mTime: String = intent.getStringExtra("time") ?: ""
        val mStatus: String = intent.getStringExtra("status") ?: ""
        val mPlace: String = intent.getStringExtra("place") ?: ""

        if (mName.isNotEmpty()) {
            mUserBean.name = mName
            mUserBean.gender = mGender
            mUserBean.birthday = mBirth
            mUserBean.bornTime = mTime
            mUserBean.marial_status = mStatus
            mUserBean.bornPlace = mPlace
        } else {
            mUserBean = AppSettingManager.readObject("user_info")!!
        }
    }

    private fun initRecycler(recycler: RecyclerView) {
        recycler.addItemDecoration(ItemDecorationToBottom(20))
        recycler.layoutManager = LinearLayoutManager(this)
        contentAdapter = ContentAdapter(this)
        recycler.adapter = contentAdapter
        contentAdapter!!.setOnItemClickedListener(object : OnItemClickedListener {
            override fun onItemClick(view: View, position: Int, string: String) {
                showLoading()
                // 协程延迟一秒
                job = GlobalScope.launch(Dispatchers.Main) {
                    val isShow = ADRewardManager.mInstance.showRewardAD(
                        TYPE, this@BirthChatActivity, position, TYPE
                    )
                    delay((1500L..3000L).random())
                    if (isShow) {
                        showLoaded()
                    } else {
                        showLoaded()
                        ToastUtil.showRewardError(this@BirthChatActivity)
                    }
                }

            }
        })
    }

    private fun initRecycler2(recycler: RecyclerView) {
        recycler.layoutManager = LinearLayoutManager(this)
        aspectAdapter = AspectAdapter(this)
        recycler.adapter = aspectAdapter

    }

    private fun loading() {
        root_birth_chart.visibility = View.INVISIBLE
        frame_layout_loading_bg?.visibility = View.VISIBLE
        loading_out.visibility = View.VISIBLE
        loading?.startAnimation(MyAnimationUtils.loadingAnimation())
        loading?.visibility = View.VISIBLE
    }

    private fun loaded() {
        root_birth_chart.visibility = View.VISIBLE
        frame_layout_loading_bg?.visibility = View.INVISIBLE
        loading_out.visibility = View.INVISIBLE
        loading?.clearAnimation()
        loading?.visibility = View.INVISIBLE
    }

    // 头部图片
    private fun request(ub: UserBean) {
        loading()
        if (ub.name.isEmpty()) ub.name = "Your name"
        if (ub.birthday.isEmpty()) {
            ub.birthday = "01-03-2000"
        }
        NetworkEngine.getBirthChart(ub.name,
            ub.cityInfo.bbox.north,
            ub.cityInfo.bbox.west,
            ub.cityInfo.timezone.gmtOffset,
            ub.birthday,
            ub.bornPlace,
            ub.cityInfo.timezone.timeZoneId,
            object : NetworkListener<BirthChartResultBean>() {
                override fun onSuccess(t: BirthChartResultBean) {
                    loaded()
                    if (t.data.report.size > 0) {
                        text_view_title_1.visibility = View.VISIBLE
                        text_view_calculate.visibility = View.VISIBLE
                        image_view_chart.visibility = View.VISIBLE
                        tv_aspect.visibility = View.VISIBLE
                        include_error.visibility = View.GONE
                        contentAdapter?.setData(t.data.report)
                        contentAdapter?.setName(t.data.horoscope)
                        aspectAdapter?.setData(t.data.aspects)
                        if (t.data.image.isNullOrEmpty()) {
                            image_view_chart.setImageResource(R.mipmap.icon_google_play)
                        } else {
                            val bitmap = SysUtils.stringtoBitmap(t.data.image)
                            if (bitmap != null) ImageLoader.loadBitmap(
                                this@BirthChatActivity,
                                image_view_chart,
                                bitmap
                            )
                        }
                        try {
                            if (intent.getBooleanExtra("Alarm", false)) { // 结束任务
                                WorkManager.getInstance(this@BirthChatActivity)
                                    .cancelUniqueWork(intent.getStringExtra("workName"))
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    } else {
                        errorMake()
                    }
                }

                override fun onFailed(t: BirthChartResultBean) {
                    super.onFailed(t)
                    errorMake()
                }

                override fun onError(e: String?) {
                    super.onError(e)
                    errorMake()
                }
            })
    }

    private fun errorMake() {
        text_view_title_1.visibility = View.INVISIBLE
        text_view_calculate.visibility = View.GONE
        image_view_chart.visibility = View.INVISIBLE
        tv_aspect.visibility = View.GONE
        include_error.visibility = View.VISIBLE
        loaded()
    }

    companion object {
        private const val TYPE = "RewardsVideo_Astrology"
        private const val TEMP_USER_BEAN = "temp_user_bean"
        fun generateIntent(context: Context, bean: UserBean): Intent {
            val intent = Intent(context, BirthChatActivity::class.java)
            val bundle = Bundle()
            bundle.putSerializable(TEMP_USER_BEAN, bean)
            intent.putExtras(bundle)
            return intent
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent) //必须
        if (intent != null) {
            initViewAndData()
            // 页面回滚到顶部
            root_birth_chart.fullScroll(ScrollView.FOCUS_UP)
        }
    }

    override fun onStop() {
        super.onStop()
        job?.cancel() // 取消协程
    }

}
